// middleware/logging.ts
import { NextRequest, NextResponse } from 'next/server'

export async function handleLogging(request: NextRequest, response: NextResponse) {
  const startTime = Date.now()
  const { pathname, search } = request.nextUrl
  const method = request.method

  // 记录请求开始信息
  console.log(`[${new Date().toISOString()}] ${method} ${pathname}${search}`)

  // 记录请求信息
  console.log('Request details:', {
    url: request.url,
    method: method,
    pathname: pathname,
    searchParams: Object.fromEntries(request.nextUrl.searchParams),
    userAgent: request.headers.get('user-agent'),
    referer: request.headers.get('referer'),
    ip: request.ip || request.headers.get('x-forwarded-for'),
  })

  // 计算处理时间
  const duration = Date.now() - startTime
  console.log(`Request processed in ${duration}ms`)

  // 添加一些请求信息到响应头中（可选）
  response.headers.set('x-request-time', startTime.toString())
  response.headers.set('x-process-duration', duration.toString())

  // 添加 Server-Timing header
  response.headers.set('Server-Timing', 'req-start;dur=0')

  return response
}
